package org.github.config;

import com.google.common.collect.ImmutableList;
import lombok.val;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;

@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean<CorsFilter> ajaxCorsFilter() {
        val allowed = ImmutableList.of("*");
        val config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOriginPatterns(allowed);
        config.setAllowedMethods(allowed);
        config.setAllowedHeaders(allowed);

        val source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        val filter = new FilterRegistrationBean<>(new CorsFilter(source));
        filter.setOrder(HIGHEST_PRECEDENCE);
        return filter;
    }
}
